package no.uib.jsparklines;

import java.awt.Color;
import java.awt.Component;
import java.awt.Toolkit;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import no.uib.jsparklines.renderers.JSparklinesBubbleHeatMapTableCellRenderer;
import no.uib.jsparklines.renderers.JSparklinesBarChartTableCellRenderer;
import no.uib.jsparklines.renderers.util.GradientColorCoding;
import no.uib.jsparklines.renderers.util.GradientColorCoding.ColorGradient;
import org.jfree.chart.plot.PlotOrientation;

/**
 * Demo of JSparklines used to display heat maps in Java tables.
 *
 * @author Harald Barsnes
 */
public class JSparklinesHeatMapDemo extends javax.swing.JFrame {

    /**
     * Sets up the heat map demo.
     */
    public JSparklinesHeatMapDemo() {

        // set up the GUI
        initComponents();

        // set additional GUI properties
        setAdditionalGuiProperties();

        // add data to the heat map
        addHeatmapValues(50);

        // set the JSparklines renderer for the columns
        for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
            heatmapJTable.getColumn(heatmapJTable.getColumnName(i)).setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, -100d, 100d));
            ((JSparklinesBarChartTableCellRenderer) heatmapJTable.getColumn(heatmapJTable.getColumnName(i)).getCellRenderer()).showAsHeatMap(ColorGradient.RedBlackGreen, false);
        }

        // make sure that the selected background color is used
        backgoundColorJComboBoxActionPerformed(null);

        // set the column with and row height such that the bubbles become circular
        heatmapJTable.setRowHeight(heatmapJTable.getColumn("1").getWidth() - 25);

        // remove the column header
        heatmapJScrollPane.setColumnHeaderView(null);
    }

    /**
     * Set up some additional GUI properties.
     */
    private void setAdditionalGuiProperties() {

        // add the gradient colors to the gradient color combo box
        colorGradientJComboBox.setModel(new DefaultComboBoxModel(GradientColorCoding.ColorGradient.values()));

        // centerally align the text in the combo boxes
        colorGradientJComboBox.setRenderer(new ComboBoxListCellRenderer());
        backgoundColorJComboBox.setRenderer(new ComboBoxListCellRenderer());
        heatmapTypeJComboBox.setRenderer(new ComboBoxListCellRenderer());

        // disable the moving of columns
        heatmapJTable.getTableHeader().setReorderingAllowed(false);

        // set the dialog icon and title
        this.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/line_plot.GIF")));
        this.setTitle("JSparklines " + getVersion() + " - Heat Map Demo");

        // make the viewports see-through (to show the gradient background)
        heatmapJScrollPane.getViewport().setOpaque(false);

        // locate the dialog in the middle of the screen
        setLocationRelativeTo(null);
    }

    /**
     * Add data to the heat map.
     */
    private void addHeatmapValues(int maxValue) {

        Random random = new Random();

        for (int i = 0; i < heatmapJTable.getColumnCount() + 2; i++) {

            ((DefaultTableModel) heatmapJTable.getModel()).addRow((new Object[]{null, null, null, null, null, null, null, null, null}));

            for (int j = 0; j < heatmapJTable.getColumnCount(); j++) {

                // randomly make the number negative or positive
                if (random.nextInt(2) == 0) {
                    ((DefaultTableModel) heatmapJTable.getModel()).setValueAt(new Double(-random.nextInt(maxValue)), i, j);
                } else {
                    ((DefaultTableModel) heatmapJTable.getModel()).setValueAt(new Double(random.nextInt(maxValue)), i, j);
                }
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        backgroundPanel = new javax.swing.JPanel();
        singleValuesJPanel = new javax.swing.JPanel();
        showHeatmapJCheckBox = new javax.swing.JCheckBox();
        heatmapJScrollPane = new javax.swing.JScrollPane();
        heatmapJTable = new JTable() {
            public boolean getScrollableTracksViewportHeight( )
            {
                return true;
            }
        };
        colorGradientJComboBox = new javax.swing.JComboBox();
        backgoundColorJComboBox = new javax.swing.JComboBox();
        heatmapTypeJComboBox = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("JSparklines Heat Map Demo");
        setResizable(false);

        backgroundPanel.setBackground(new java.awt.Color(255, 255, 255));

        singleValuesJPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Heat Map"));
        singleValuesJPanel.setOpaque(false);

        showHeatmapJCheckBox.setSelected(true);
        showHeatmapJCheckBox.setText("Heat Map");
        showHeatmapJCheckBox.setToolTipText("Turn the heat map on or off");
        showHeatmapJCheckBox.setIconTextGap(8);
        showHeatmapJCheckBox.setOpaque(false);
        showHeatmapJCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showHeatmapJCheckBoxActionPerformed(evt);
            }
        });

        heatmapJScrollPane.setOpaque(false);

        heatmapJTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        heatmapJTable.setFillsViewportHeight(true);
        heatmapJTable.setRowSelectionAllowed(false);
        heatmapJTable.setSelectionBackground(new java.awt.Color(204, 204, 204));
        heatmapJTable.setShowHorizontalLines(false);
        heatmapJTable.setShowVerticalLines(false);
        heatmapJScrollPane.setViewportView(heatmapJTable);

        colorGradientJComboBox.setMaximumSize(new java.awt.Dimension(48, 20));
        colorGradientJComboBox.setOpaque(false);
        colorGradientJComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                colorGradientJComboBoxActionPerformed(evt);
            }
        });

        backgoundColorJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "White", "Black" }));
        backgoundColorJComboBox.setSelectedIndex(1);
        backgoundColorJComboBox.setMaximumSize(new java.awt.Dimension(48, 20));
        backgoundColorJComboBox.setOpaque(false);
        backgoundColorJComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backgoundColorJComboBoxActionPerformed(evt);
            }
        });

        heatmapTypeJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bubble", "Area" }));
        heatmapTypeJComboBox.setSelectedIndex(1);
        heatmapTypeJComboBox.setMaximumSize(new java.awt.Dimension(48, 20));
        heatmapTypeJComboBox.setOpaque(false);
        heatmapTypeJComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                heatmapTypeJComboBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout singleValuesJPanelLayout = new javax.swing.GroupLayout(singleValuesJPanel);
        singleValuesJPanel.setLayout(singleValuesJPanelLayout);
        singleValuesJPanelLayout.setHorizontalGroup(
            singleValuesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, singleValuesJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(singleValuesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(heatmapJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 744, Short.MAX_VALUE)
                    .addGroup(singleValuesJPanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(heatmapTypeJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(backgoundColorJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(colorGradientJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(showHeatmapJCheckBox)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        singleValuesJPanelLayout.setVerticalGroup(
            singleValuesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, singleValuesJPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(heatmapJScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(singleValuesJPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(showHeatmapJCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(colorGradientJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(backgoundColorJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(heatmapTypeJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9))
        );

        javax.swing.GroupLayout backgroundPanelLayout = new javax.swing.GroupLayout(backgroundPanel);
        backgroundPanel.setLayout(backgroundPanelLayout);
        backgroundPanelLayout.setHorizontalGroup(
            backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(singleValuesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        backgroundPanelLayout.setVerticalGroup(
            backgroundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backgroundPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(singleValuesJPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(backgroundPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Turns the heat map renderer on or off. When turned off the underlying
     * values are shown.
     *
     * @param evt
     */
    private void showHeatmapJCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showHeatmapJCheckBoxActionPerformed

        // enable or disable to heat map combo boxes
        heatmapTypeJComboBox.setEnabled(showHeatmapJCheckBox.isSelected());
        backgoundColorJComboBox.setEnabled(showHeatmapJCheckBox.isSelected());
        colorGradientJComboBox.setEnabled(showHeatmapJCheckBox.isSelected());

        // update the gradient color
        if (heatmapTypeJComboBox.getSelectedIndex() == 0) {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                ((JSparklinesBubbleHeatMapTableCellRenderer) heatmapJTable.getColumn(
                        heatmapJTable.getColumnName(i)).getCellRenderer()).showNumbers(!showHeatmapJCheckBox.isSelected());
            }
        } else {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                ((JSparklinesBarChartTableCellRenderer) heatmapJTable.getColumn(
                        heatmapJTable.getColumnName(i)).getCellRenderer()).showNumbers(!showHeatmapJCheckBox.isSelected());
            }
        }

        // repaint the table to update the plot
        heatmapJTable.revalidate();
        heatmapJTable.repaint();
    }//GEN-LAST:event_showHeatmapJCheckBoxActionPerformed

    /**
     * Updates the color gradient.
     *
     * @param evt
     */
    private void colorGradientJComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorGradientJComboBoxActionPerformed

        ColorGradient[] colorGradients = GradientColorCoding.ColorGradient.values();
        ColorGradient colorGradient = colorGradients[colorGradientJComboBox.getSelectedIndex()];

        // update the gradient color
        if (heatmapTypeJComboBox.getSelectedIndex() == 0) {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                ((JSparklinesBubbleHeatMapTableCellRenderer) heatmapJTable.getColumn(
                        heatmapJTable.getColumnName(i)).getCellRenderer()).setGradientColoring(colorGradient, false);
            }
        } else {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                ((JSparklinesBarChartTableCellRenderer) heatmapJTable.getColumn(
                        heatmapJTable.getColumnName(i)).getCellRenderer()).setGradientColoring(colorGradient, false);
            }
        }

        // repaint the table to update the plot
        heatmapJTable.revalidate();
        heatmapJTable.repaint();
}//GEN-LAST:event_colorGradientJComboBoxActionPerformed

    /**
     * Updates the background color used in the plots.
     *
     * @param evt
     */
    private void backgoundColorJComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backgoundColorJComboBoxActionPerformed

        if (((String) backgoundColorJComboBox.getSelectedItem()).equalsIgnoreCase("Black")) {
            heatmapJTable.setGridColor(Color.BLACK);
            heatmapJTable.setBackground(Color.BLACK);
            heatmapJTable.setOpaque(true);
            heatmapJTable.setForeground(Color.WHITE);
        } else { // white
            heatmapJTable.setGridColor(Color.WHITE);
            heatmapJTable.setBackground(Color.WHITE);
            heatmapJTable.setOpaque(true);
            heatmapJTable.setForeground(Color.BLACK);
        }

        // repaint the table to update the plot
        heatmapJTable.revalidate();
        heatmapJTable.repaint();
    }//GEN-LAST:event_backgoundColorJComboBoxActionPerformed

    /**
     * Update the heat map type.
     *
     * @param evt
     */
    private void heatmapTypeJComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_heatmapTypeJComboBoxActionPerformed

        ColorGradient[] colorGradients = GradientColorCoding.ColorGradient.values();
        ColorGradient colorGradient = colorGradients[colorGradientJComboBox.getSelectedIndex()];

        if (heatmapTypeJComboBox.getSelectedIndex() == 0) {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                heatmapJTable.getColumn(heatmapJTable.getColumnName(i)).setCellRenderer(new JSparklinesBubbleHeatMapTableCellRenderer(100d, colorGradient, false));
            }
        } else {
            for (int i = 0; i < heatmapJTable.getColumnCount(); i++) {
                heatmapJTable.getColumn(heatmapJTable.getColumnName(i)).setCellRenderer(new JSparklinesBarChartTableCellRenderer(PlotOrientation.HORIZONTAL, -100d, 100d));
                ((JSparklinesBarChartTableCellRenderer) heatmapJTable.getColumn(heatmapJTable.getColumnName(i)).getCellRenderer()).showAsHeatMap(colorGradient, false);
            }
        }

        // repaint the table to update the plot
        heatmapJTable.revalidate();
        heatmapJTable.repaint();
    }//GEN-LAST:event_heatmapTypeJComboBoxActionPerformed

    /**
     * Starts the JSparklines heat map demo.
     *
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        
        /* Set the Nimbus look and feel */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            // ignore, use default look and feel
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JSparklinesHeatMapDemo().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox backgoundColorJComboBox;
    private javax.swing.JPanel backgroundPanel;
    private javax.swing.JComboBox colorGradientJComboBox;
    private javax.swing.JScrollPane heatmapJScrollPane;
    private javax.swing.JTable heatmapJTable;
    private javax.swing.JComboBox heatmapTypeJComboBox;
    private javax.swing.JCheckBox showHeatmapJCheckBox;
    private javax.swing.JPanel singleValuesJPanel;
    // End of variables declaration//GEN-END:variables

    /**
     * Retrieves the version number set in the pom file.
     *
     * @return the version number of JSparklines
     */
    public String getVersion() {

        java.util.Properties p = new java.util.Properties();

        try {
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("jsparklines.properties");
            p.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return p.getProperty("jsparklines.version");
    }

    /**
     * An non-opaque cell renderer, making the panel behind the table visible.
     */
    public class NonOpaqueCellRenderer extends DefaultTableCellRenderer {

        public Component getTableCellRendererComponent(JTable table, Object value,
                boolean isSelected, boolean hasFocus, int row, int column) {

            JComponent c = (JComponent) super.getTableCellRendererComponent(table, value,
                    isSelected, hasFocus, row, column);
            ((JComponent) c).setOpaque(isSelected);
            return c;
        }
    }

    /**
     * A simple combo box render making sure that the combo boxes looks good
     * with the current gradient background.
     */
    public class ComboBoxListCellRenderer extends DefaultListCellRenderer {

        public Component getListCellRendererComponent(
                JList list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {

            JLabel c = (JLabel) super.getListCellRendererComponent(
                    list, value, index, isSelected, cellHasFocus);

            ((JComponent) c).setOpaque(isSelected);

            if (isSelected || cellHasFocus) {
                c.setBackground(Color.LIGHT_GRAY);
            }

            c.setHorizontalAlignment(SwingConstants.CENTER);

            return c;
        }
    }
}
